#!/bin/bash
# Michael P. Reilly (C) 2015 All rights reserved
# bash command completion script
# release $RelNo$ ($Revision$)

# if there are multiple data files, add them here
# if there are multiple programs with different names, add them below
DATAFILES="$HOME/etc/server.lst"

LOGFILE=/tmp/svrfilter_comp.log

if [ ! -d $HOME/.cache/bash_completion ]; then
    mkdir -p $HOME/.cache/bash_completion
fi
COMP_CACHE=$HOME/.cache/bash_completion/svrfilter

# cache info
# unfortunately, we don't know if --file arguments will be used so we need
# to cache values from the standard files
test -f $COMP_CACHE
do_cache=$?
for dfile in $DATAFILES; do
    if [ $do_cache -eq 0 -a $dfile -nt $COMP_CACHE ]; then
        do_cache=1
    fi
done
if [ $do_cache -ne 0 ]; then
    cache_prog="${TMPDIR-/tmp}/svrfilter_cache_$$.py"
    cat > ${cache_prog} <<'EOF'
import os, sys
prods, envs, nets, hosts, users, brdgs = {}, {}, {}, {}, {}, {}
fields = ("active", "apptools", "bridge", "domain", "env", "fqdn",
          "host", "hostname", "net", "ordinal", "prod", "product",
          "user", "userhost", "username")
envvalues = ("dev", "load", "prod", "stag", "test")
for line in sys.stdin:
    line = line.strip()
    if line.startswith("#") or line == "": continue
    parts = line.split("|")
    fvar = (parts[1] in envvalues) and 2 or 1
    if fvar == 2:
        prods[parts[0]] = envs[parts[1]] = hosts[parts[2]] = users[parts[3]] = nets[parts[4]] = None
    else:
        prods[parts[2]] = None
        envs[parts[0]] = hosts[parts[1]] = users[parts[2]] = nets[parts[3]] = None
    if len(parts) > (fvar == 2 and 7 or 6): brdgs[parts[fvar == 2 and 6 or 5]] = None
if "?" in users: del users["?"]
print "_svrfilter_prods=\"%s\"" % " ".join(sorted(prods))
print "_svrfilter_envs=\"%s\"" % " ".join(sorted(envs))
print "_svrfilter_hosts=\"%s\"" % " ".join(sorted(hosts))
print "_svrfilter_users=\"%s\"" % " ".join(sorted(users))
print "_svrfilter_nets=\"%s\"" % " ".join(sorted(nets))
print "_svrfilter_brdgs=\"%s\"" % " ".join(sorted(brdgs))
print "_svrfilter_fields=\"%s\"" % " ".join(sorted(fields))
EOF
    cat $DATAFILES | python ${cache_prog} > $COMP_CACHE
    rm -f ${cache_prog}
    unset cache_prog
fi
. $COMP_CACHE
unset COMP_CACHE

_svrfilter_shortopts="-B -c -C -e -f -F -h -H -n -p -R -s -u -U -v"
_svrfilter_longopts="--active --apptools --bridge --check --comment\
 --config --DEBUG --env --file --filter --help --host --inactive --net\
 --noapptools --primary --product --prod --raw --secondary --sort\
 --unique --user --verbose --version"

_svrfilter () {
    local cur prev prevprev
    COMPREPLY=()
    cur=${COMP_WORDS[COMP_CWORD]}
    prev=${COMP_WORDS[COMP_CWORD-1]}
    if [ $COMP_CWORD -ge ${#COMP_WORDS} ]; then
        prevprev=${COMP_WORDS[COMP_CWORD-2]}
    else
        prevprev=${COMP_WORDS[0]}
    fi

    if [[ $cur == --* ]]; then    # long options
        COMPREPLY=(
                $(compgen -W "${_svrfilter_longopts}" -- "$cur")
        )
    elif [[ $cur == -* ]]; then   # short options
        COMPREPLY=(
                $(compgen -W "${_svrfilter_shortopts} ${_svrfilter_longopts}" -- "$cur" )
            )
    elif [ "X$prev" = "X--file" -o "X$prev" = "X-f" ] ||
         [ "X$prevprev" = "X--file" -a "X$prev" = "X=" ]; then  # --file|-f
        if [[ $cur == "" ]]; then
            COMPREPLY=( $(compgen -f -o filenames) )
        elif [[ $cur == \~*/* ]]; then
            cur=${cur#\~/}
            COMPREPLY=( $(cd 2>/dev/null; compgen -P \~/ -o filenames -G "$cur*") )
        else
            COMPREPLY=( $(compgen -o filenames -G "$cur"*) )
        fi
    elif [ "X$prev" = "X--config" ] ||
         [ "X$prevprev" = "X--config" -a "$Xprev" = "X=" ]; then # --config
        if [[ $cur == "" ]]; then
            COMPREPLY=( $(compgen -f -o filenames) )
        elif [[ $cur == \~*/* ]]; then
            cur=${cur#\~/}
            COMPREPLY=( $(cd 2>/dev/null; compgen -P \~/ -o filenames -G "$cur"*) )
        else
            COMPREPLY=( $(compgen -o filenames -G "$cur"*) )
        fi
    elif [ "X$prev" = "X--sort" -o "X$prev" = "X-S" ] ||
         [ "X$prevprev" = "X--sort" -a "X$prev" = "X=" ]; then # --sort|-S
        COMPREPLY=( $(compgen -W "$_svrfilter_fields" -- "$cur") )
    elif [ "X$prev" = "X--comment" -o "X$prev = "X-c" ] ||
         [ "X$prevprev" = "X--comment" -a X$prev" = "X=" ]; then # --comment|-c
        COMPREPLY=( $(compgen -W "$_svrfilter_fields" -- "$cur") )
    elif [ "X$prev" = "X--unique" -o "X$prev" = "X-U" ] ||
         [ "X$prevprev" = "X--unique" -a "X$prev" = "X=" ]; then  # --unique|-U
        COMPREPLY=( $(compgen -W "$_svrfilter_fields" -- "$cur") )
    elif [ "X$prev" = "X--product" -o "X$prev" = "X--prod" -o "X$prev" = "X-p" ] ||
         [ "X$prevprev" = "X--product" -a "X$prev" = "X=" ] ||
         [ "X$prevprev" = "X--prod" -a "X$prev" = "X=" ]; then # --product|-p
        COMPREPLY=( $(compgen -W "$_svrfilter_prods" -- "$cur") )
    elif [ "X$prev" = "X--env" -o "X$prev" = "X-e" ] ||
         [ "X$prevprev" = "X--env" -a "X$prev" = "X=" ]; then  # --env|-e
        COMPREPLY=( $(compgen -W "$_svrfilter_envs" -- "$cur") )
    elif [ "X$prev" = "X--net" -o "X$prev" = "X-n" ] ||
         [ "X$prevprev" = "X--net" -a "X$prev" = "X=" ]; then  # --net|-n
        COMPREPLY=( $(compgen -W "$_svrfilter_nets" -- "$cur") )
    elif [ "X$prev" = "X--user" -o "X$prev" = "X-u" ] ||
         [ "X$prevprev" = "X--user" -a "X$prev" = "X=" ]; then  # --user|-u
        COMPREPLY=( $(compgen -W "$_svrfilter_users" -- "$cur") )
    elif [ "X$prev" = "X--host" -o "X$prev" = "X-H" ] ||
         [ "X$prevprev" = "X--host" -a "X$prev" = "X=" ]; then  # --host|-H
        COMPREPLY=( $(compgen -W "$_svrfilter_hosts" -- "$cur") )
    elif [ "X$prev" = "X--bridge" -o "X$prev" = "X-B" ] ||
         [ "X$prevprev" = "X--bridge" -a "X$prev" = "X=" ]; then  # --bridge|-B
        COMPREPLY=( $(compgen -W "$_svrfilter_brdgs" -- "$cur") )
    fi
    # uncomment for debugging
    #echo "$COMP_CWORD|$cur|$prev|$prevprev" >> $LOGFILE
    #echo "X${COMPREPLY[*]}" >> $LOGFILE
    return 0
}

# uncomment for debugging
#echo "restarting svrfilter.comp" >> $LOGFILE

complete -F _svrfilter svrfilter

